package com.xiaobingby.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.xiaobingby.common.base.BaseController;
import com.xiaobingby.common.result.JsonResult;
import com.xiaobingby.controller.view.DataTables;
import com.xiaobingby.entity.QueryCondition;
import com.xiaobingby.entity.Role;
import com.xiaobingby.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author XiaoBingBy
 * @since 2017-07-23
 */
@Controller
@RequestMapping("/admin/role")
public class RoleController extends BaseController {

    @Autowired
    private IRoleService iRoleService;

    @RequestMapping("/list")
    public String list(Model model) {
        return "/admin/role/list";
    }

    @ResponseBody
    @RequestMapping("/getRoleList")
    public DataTables<Role> getUserList(QueryCondition query) {
        Page<Role> page = new Page<Role>(query.getStart()/query.getLength()+1, query.getLength());
        EntityWrapper<Role> wrapper = new EntityWrapper<>();
        if (query.getKeyword() != null)
            wrapper.like("name", query.getKeyword().trim());
        Page<Role> rolePage = iRoleService.selectPage(page, wrapper);
        DataTables<Role> result = new DataTables<Role>();
        result.setDraw(query.getDraw());
        result.setRecordsTotal(rolePage.getTotal());
        result.setRecordsFiltered(rolePage.getTotal());
        result.setData(rolePage.getRecords());
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/save")
    public JsonResult save(Role role) {
        if (role.getId() == null) {
            return iRoleService.insert(role) ? renderSuccess("添加成功") : renderError("添加失败");
        } else {
            return iRoleService.updateById(role) ? renderSuccess("修改成功") : renderError("修改失败");
        }
    }

    @ResponseBody
    @RequestMapping("/delete")
    public Object delete(@RequestParam(value = "id", required = false) Integer id) {
        return iRoleService.deleteById(id) ? renderSuccess("删除成功") : renderError("删除失败");
    }

}
